const db = require('../db/index')

// 立即支付订单
exports.PayOrder = (req, res) => {
  // const sql = `INSERT INTO pet_shop.order(uid, No, pet_name, pet_price, pet_num, pet_color, pet_place, order_img) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`
  const sql = `INSERT INTO pet_order set uid = ?, No = ?, pet_name = ?, pet_price = ?, pet_num = ?, pet_color = ?, pet_place = ?, order_img = ?`
  db.query(sql, [req.body.uid, req.body.No, req.body.pet_name, req.body.pet_price, req.body.pet_num, req.body.pet_color, req.body.pet_place, req.body.order_img], (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) return res.cc('支付失败！')
    res.cc('支付成功！', 0)
    console.log(req.body)
  })
}

// 获取用户订单
exports.getUserOrder = (req, res) => {
  // 每页几条数据
  let pagesize = 5
  // 当前页码数
  let pagenum = (req.query.pagenum - 1) * pagesize
  let datas = []
  const sql = `SELECT * FROM pet_order  WHERE uid = ? and isCancel = 0 limit ${pagenum},${pagesize}`
  const sql2 = `select count(*) as total from pet_order where uid = ?`
  db.query(sql, req.query.uid, (err, results) => {
    if (err) return res.cc(err)
    if (results.length < 0) return res.cc('获取用户订单失败！')
    datas = results
    db.query(sql2, req.query.uid, (err, result) => {
      if (err) return res.cc(err)
      if (result.length < 0) return res.cc('获取用户订单失败！')
      res.send({
        status: 0,
        message: '获取用户订单成功！',
        data: datas,
        total: result[0]
      })
    })
  })
}

// 用户申请退货
exports.applyForReturn = (req, res) => {
  console.log('req.body.oid', req.body.oid)
  const sql = `update pet_order set isReturn = 1 where oid = ?`
  db.query(sql, [req.body.oid], (err, results) => {
    if (err) return res.cc(err)
    if (results.length < 0) return res.cc('申请退货失败！')
    res.send({
      status: 0,
      message: '申请退货成功！'
    })
  })
}
